package com.hong.controller.system;

import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hong.common.AjaxResultVo;
import com.hong.common.controller.BaseController;
import com.hong.entity.SysLog;
import com.hong.service.ISysLogService;

@Controller
@RequestMapping("/system/log")
public class LogController extends BaseController {

	@Autowired
	private ISysLogService sysLogService;

	/**
	 * 跳转日志页面
	 * 
	 * @return
	 */
	@RequiresPermissions("listLog")
	@RequestMapping("/listPage")
	public String listPage() {
		return "system/log/list";
	}

	/**
	 * 分页查询日志
	 * 
	 * @param search    检索条件
	 * @param daterange 时间范围筛选
	 * @param limit     每页条数
	 * @param offset    偏移值
	 * @return
	 */
	@RequiresPermissions("listLog")
	@RequestMapping("/listLog")
	@ResponseBody
	public AjaxResultVo listLog(String search, String daterange, Integer limit, Integer offset) {
		QueryWrapper<SysLog> ew = new QueryWrapper<SysLog>();
		if (StringUtils.isNotBlank(search)) {
			ew.like("user_name", search);
		}
		String[] dateranges = {};
		if (StringUtils.isNotBlank(daterange)) {
			dateranges = StringUtils.split(daterange, "~");
			ew.between("create_time", dateranges[0].trim(), dateranges[1].trim());
		}
		ew.orderByDesc("create_time");
		PageHelper.startPage(getPageNo(limit, offset), limit);
		List<SysLog> logList = sysLogService.list(ew);
		PageInfo<SysLog> pageData = new PageInfo<>(logList);
		AjaxResultVo resultVo = AjaxResultVo.success();
		resultVo.put("total", pageData.getTotal());
		resultVo.put("rows", pageData.getList());
		return resultVo;
	}

	/**
	 * 查看详情
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/params/{id}")
	public String params(@PathVariable String id, Model model) {
		SysLog sysLog = sysLogService.getById(id);
		model.addAttribute("sysLog", sysLog);
		return "system/log/logdetail";
	}

	/**
	 * 批量删除日志
	 * 
	 * @param ids
	 * @return
	 */
	@RequiresPermissions("deleteLog")
	@RequestMapping("/deleteBatch")
	@ResponseBody
	public AjaxResultVo deleteBatch(@RequestParam("id[]") List<String> ids) {
		if (ObjectUtils.isEmpty(ids)) {
			return AjaxResultVo.error("参数错误");
		}
		if (sysLogService.removeByIds(ids)) {
			return AjaxResultVo.success();
		} else {
			return AjaxResultVo.error();
		}
	}

}
